#include "tilesystem.h"

#include <fstream>

namespace griselda
{
    namespace map
    {
        /**
         * Creates a tile, adds it to the container and returns its ID
         *
         * @todo   actually create a tile
         * @param  pos position on chipset
         * @param  tl tile layer of the new tile
         * @return id of the new tile
         */
        const tile_id tile_container::create_tile()
        {
            map_tile tile;
            m_tile_vec.push_back(tile);
            return (m_tile_vec.size() - 1);
        }
        
        /**
         * Returns a const reference to the tile with [id].
         *
         * @param  id ID of the tile
         * @return the tile
         */
        const map_tile& tile_container::tile(tile_id id) const
        {
            return m_tile_vec[id];
        }

        /**
         * Edits an existing tile.
         *
         * @param  id id of the tile to edit
         * @param  tile new tile
         * @return false if tile doesn't exist, true otherwise
         */
        bool tile_container::set_tile(tile_id id, const map_tile& tile)
        {
            if(id >= m_tile_vec.size())
                return false;

            m_tile_vec[id] = tile;
            return true;
        }

        /**
         * Removes a tile from the container.
         * Make sure that no map contains that tile anymore!
         *
         * @param  id ID of the tile to remove
         * @return false if the tile does not exist, true otherwise
         */
        bool tile_container::remove_tile(tile_id id)
        {
            if(id >= m_tile_vec.size())
                return false;

            m_tile_vec.erase(m_tile_vec.begin() + id);
            return true;
        }

        bool save_tiles(const tile_container& tc, const std::string& fn)
        {
            std::ofstream ostr(fn.c_str());
            if(!ostr.good())
                return false;

            // save all tiles
            for(int i = 0; i < tc.count(); ++i)
            {
                const map_tile& t = tc.tile(i);
                //ostr << t.pos.x << ";" << t.pos.y << ";" << t.layer << ";" << std::endl;
            }

            ostr.close();

            return true;
        }
    }
}
